package com.xinsoft.jwt;

import com.github.pagehelper.util.StringUtil;
import com.xinsoft.entity.po.SysUser;
import com.xinsoft.utils.RedisUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author hsm
 * @description jwt工具类
 * @createDate 2023-04-24
 */
@Data
@ConfigurationProperties(prefix = "jwt")
@Component
public class JwtTokenUtil {
    private String secret;

    private Long expiration;

    private String header;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 生成token令牌
     *
     * @param user 用户
     * @return 令牌token
     */
    public String generateToken(SysUser user) {
        Map<String, Object> claims = new HashMap<>(2);
        claims.put("userId", user.getId());
        claims.put("sub", user.getUsername());
        claims.put("realName", user.getRealName());
        claims.put("deptId", user.getDeptId());
        claims.put("created", new Date());
        claims.put("clerkId", user.getClerkId());
        return generateToken(claims);
    }

    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public String getUsernameFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    /**
     * 判断令牌是否过期
     *
     * @param token 令牌
     * @return 是否过期
     */
    public Boolean isTokenExpired(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            Date expiration = claims.getExpiration();
            return expiration.before(new Date());
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 刷新令牌
     *
     * @param token 原令牌
     * @return 新令牌
     */
    public String refreshToken(String token) {
        String refreshedToken;
        try {
            Claims claims = getClaimsFromToken(token);
            claims.put("created", new Date());
            refreshedToken = generateToken(claims);
        } catch (Exception e) {
            refreshedToken = null;
        }
        return refreshedToken;
    }

    /**
     * 验证令牌
     *
     * @param token       令牌
     * @param userDetails 用户
     * @return 是否有效
     */
    public Boolean validateToken(String token, UserDetails userDetails) {
        String username = getUsernameFromToken(token);
        return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
    }

    /**
     * 从claims生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String generateToken(Map<String, Object> claims) {
        Date expirationDate = new Date(System.currentTimeMillis() + expiration);
        return Jwts.builder().setClaims(claims)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims getClaimsFromToken(String token) {
        Claims claims;
        try {
            claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }

    /**
     * 获取用户id
     *
     * @param request 请求域
     * @return Integer
     */
    public Integer getUserId(HttpServletRequest request) {
        String jwtToken = request.getHeader(header);
        if (StringUtil.isNotEmpty(jwtToken)) {
            Map<Object, Object> userMap = redisUtil.hmget(jwtToken);
            return (Integer) userMap.get("id");
        }
        return 0;
    }

    /**
     * 获取用户姓名
     *
     * @param request 请求域
     * @return String
     */
    public String getName(HttpServletRequest request) {
        String jwtToken = request.getHeader(header);
        if (StringUtil.isNotEmpty(jwtToken)) {
            Map<Object, Object> userMap = redisUtil.hmget(jwtToken);
            return (String) userMap.get("name");
        }
        return null;
    }

    public Map<Object, Object> getRedisMap(HttpServletRequest request) {
        String jwtToken = request.getHeader(header);
        if (StringUtil.isNotEmpty(jwtToken)) {
            return redisUtil.hmget(jwtToken);
        }
        return null;
    }
}